# from apscheduler.schedulers.blocking import BlockingScheduler
# import time
# from database.mapper import stock_info, stock_day_k, stock_day_macd, stock_monitor, stock_month_k, stock_month_macd
# from utils import date_util, k_util_v1, macd_util_v1, caiptal_util
#
#
# # 数据刷新定时任务
# def fresh_data():
#     # 启动先刷新一次任务
#     fresh_task_interval()
#     # 添加任务,时间间隔30S
#     scheduler = BlockingScheduler()
#     # 从开始时间到结束时间，每隔一小时运行一次
#     scheduler.add_job(fresh_task_interval, 'interval', seconds=1800, id='monitor_task')
#     # 开市插入新数据
#     scheduler.add_job(add_new_task, 'cron', day_of_week='0-4', hour=9, minute=31)
#     # 闭市再次刷新数据
#     scheduler.add_job(fresh_task_close, 'cron', day_of_week='0-4', hour=15, minute=15)
#     scheduler.start()
#
#
# # 开市插入新数据
# # 已完成
# def add_new_task():
#     if not date_util.valid_day(date_util.get_date_str()):
#         return
#     s_list = stock_info.selectall()
#     # 增加日K
#     add_day_k(s_list)
#     # 增加日macd
#     add_day_macd(s_list)
#
#
# # 已完成
# def add_day_k(s_list):
#     for s in s_list:
#         code = s['code']
#         day_k = stock_day_k.select(code)
#         if len(day_k) == 0:
#             k_util_v1.init_day_k(code)
#         else:
#             o_rq = day_k['rq']
#             d_rq = date_util.str_to_date(date_util.get_date_str(), '%Y-%m-%d')
#             diff_d = date_util.diff_days(o_rq, d_rq)
#             if diff_d <= 0:
#                 print('日期一致end，code' + code)
#                 continue
#             k_lines = k_util_v1.get_day_k_size(code, diff_d + 1)
#             k_len = len(k_lines)
#             if k_len == 0:
#                 continue
#             for i in range(k_len):
#                 if date_util.str_to_date(k_lines[i]['rq'], '%Y-%m-%d').date() == o_rq:
#                     # 更新当天数据
#                     stock_day_k.update(k_lines[i])
#                     # 插入剩余数据
#                     if i >= 1:
#                         stock_day_k.insert_multiple(k_lines[0: i])
#                     break
#
#
# def add_day_macd(s_list):
#     for s in s_list:
#         code = s['code']
#         day_macd = stock_day_macd.select(code)
#         if len(day_macd) == 0:
#             macd_util_v1.init_day_macd(code)
#         else:
#             o_rq = day_macd['rq']
#             d_rq = date_util.str_to_date(date_util.get_date_str(), '%Y-%m-%d')
#             diff_d = date_util.diff_days(o_rq, d_rq)
#             if diff_d <= 0:
#                 print('日期一致end，code' + code)
#                 continue
#             day_k_list = stock_day_k.select_interval(code, o_rq, d_rq)
#             # 日期从小到大
#             day_k_list.reverse()
#             macd_up_list = []
#             for day_k in day_k_list:
#                 k_rq = day_k['rq']
#                 if k_rq == o_rq:
#                     continue
#                 macd_up_list.append(macd_util_v1.cal_macd_next_v1(day_macd, k_rq, day_k['sp']))
#             stock_day_macd.insert_multiple(macd_up_list)
#
#
# # 闭市刷新数据
# def fresh_task_close():
#     if not date_util.valid_day(date_util.get_date_str()):
#         return
#     s_list = stock_info.selectall()
#     # 刷新日k,日macd
#     fresh_task(s_list)
#     # 刷新月k,月macd
#     fresh_month_info()
#     # 持久化监控数据
#     persistence_data()
#     # 刷新市值
#     fresh_stock_val()
#     print(date_util.get_date_time() + ':刷新数据结束')
#
#
# # 刷新数据
# def fresh_task_interval():
#     if not check_time():
#         return
#     s_list = stock_monitor.select_distinct()
#     fresh_task(s_list)
#
#
# # 刷新数据 日K + 日macd
# def fresh_task(s_list):
#     for stock in s_list:
#         code = stock['code']
#         print('code' + code + '开始刷新日数据')
#         # 一、刷新日K
#         k_line = k_util_v1.get_day_k_size(code, 1)
#         if not k_line or len(k_line) == 0:
#             print('code' + code + '停牌？')
#             continue
#         for k in k_line:
#             count = stock_day_k.update(k)
#             if count == 0:
#                 add_day_k([{'code': code}])
#         # 二、刷新日macd
#         for k in k_line:
#             rq = k['rq']
#             macd_list = stock_day_macd.select_newest_size(code, 2)
#             if len(macd_list) == 0 or date_util.date_to_str(macd_list[0]['rq'], '%Y-%m-%d') != rq:
#                 add_day_macd([{'code': code}])
#                 break
#             next_macd = macd_util_v1.cal_macd_next_v1(macd_list[1], rq, float(k['sp']))
#             count = stock_day_macd.update(next_macd)
#             if count == 0:
#                 add_day_macd([{'code': code}])
#
#
# # 检查有效时间
# def check_time():
#     if not date_util.valid_day(date_util.get_date_str()):
#         return 0
#     # 触发任务一（up_down_monitor）
#     date_time = date_util.get_date_time()
#     hour = date_time.hour
#     minute = date_time.minute
#     if 9 <= hour < 15 and not (hour == 9 and minute < 30) \
#             and not (hour == 11 and minute > 30) and not (hour == 12):
#         return 1
#     return 0
#
#
# # 校验数据
# def check_data():
#     s_list = stock_info.selectall()
#     count = 0
#     for s in s_list:
#         if count >= 5000:
#             return
#         code = s['code']
#         o_count = len(k_util_v1.get_day_k_size(code, 12000))
#         k_count = stock_day_k.select_count(code)
#         macd_count = stock_day_macd.select_count(code)
#         if o_count != k_count:
#             print(code + '线上和线下数据不一致')
#             stock_day_k.delete_interval(code, '1990-01-01')
#             stock_day_macd.delete_all(code)
#             count += 1
#             continue
#         if k_count != macd_count:
#             print(code + 'k+macd数据不一致')
#             stock_day_macd.delete_all(code)
#             count += 1
#
#
# # 校验macd
# def check_macd():
#     s_list = stock_info.selectall()
#     count = 0
#     for stock in s_list:
#         code = stock['code']
#         macd_list = macd_util_v1.MACD(macd_util_v1.parse_x(stock_day_k.select_all_asc(code), 'rq', 'sp'))
#         macd_list.reverse()
#         for i in range(0, min(10, len(macd_list))):
#             data_c = macd_list[i]
#             data_d = stock_day_macd.select_rq(code, data_c['rq'])
#             if round(data_c['macd'], 10) != round(data_d['macd'], 10) \
#                     or round(data_c['ema12'], 10) != round(data_d['ema12'], 10) \
#                     or round(data_c['ema26'], 10) != round(data_d['ema26'], 10) \
#                     or round(data_c['dea'], 10) != round(data_d['dea'], 10):
#                 count += 1
#                 print('error,error,error,error:' + str(count))
#                 print(str(data_c))
#                 print(str(data_d))
#                 stock_day_macd.delete_all(code)
#                 stock_day_macd.insert_multiple(macd_list)
#                 time.sleep(3)
#                 break
#
#
# # 每天刷新一次
# def fresh_month_info():
#     if not date_util.valid_day(date_util.get_date_str()):
#         return 0
#     s_list = stock_info.selectall()
#     # k
#     for stock in s_list:
#         code = stock['code']
#         mk = stock_month_k.select(code)
#         # mmacd = stock_month_macd.select(code)
#         if not mk:
#             k_util_v1.init_month_k(code)
#             continue
#         mkm = mk['rq'].month
#         mkd = mk['rq'].day
#         lvr = date_util.find_last_valid_day()
#         lvm = lvr[5:7]
#         lvd = lvr[-2:]
#         if mkm == int(lvm):
#             if mkd == int(lvd) or date_util.get_date_time().hour < 15:
#                 print(code + '同一天执行任务跳过或者当天交易未结束')
#                 continue
#             # 处理月K
#             dk = stock_day_k.select(code)
#             mk['rq'] = dk['rq']
#             mk['max'] = max(dk['max'], mk['max'])
#             mk['min'] = min(dk['min'], mk['min'])
#             mk['sp'] = dk['sp']
#             stock_month_k.update(mk)
#             # 处理月macd
#             fresh_month_macd(code, mk)
#         else:
#             # 计算上一个月K
#             dm = date_util.date_to_str(mk['rq'], '%Y-%m-%d')[0:8]
#             mb = dm + '01'
#             me = lvr[0:8] + '01'
#             dks = stock_day_k.select_interval(code, mb, me)
#             if dks:
#                 dkl = len(dks)
#                 mk['kp'] = dks[dkl - 1]['kp']
#                 mk['rq'] = dks[0]['rq']
#                 mk['sp'] = dks[0]['sp']
#                 for dk in dks:
#                     mk['max'] = max(mk['max'], dk['max'])
#                     mk['min'] = min(mk['min'], dk['min'])
#                 stock_month_k.update(mk)
#                 # 刷新月macd
#                 fresh_month_macd(code, mk)
#             # 增加最新一天月K
#             dks = stock_day_k.select_interval(code, me, date_util.add_day_str(lvr, 1))
#             if dks:
#                 dkl = len(dks)
#                 mk['kp'] = dks[dkl - 1]['kp']
#                 mk['rq'] = dks[0]['rq']
#                 mk['sp'] = dks[0]['sp']
#                 for dk in dks:
#                     mk['max'] = max(mk['max'], dk['max'])
#                     mk['min'] = min(mk['min'], dk['min'])
#                 stock_month_k.insert(mk)
#                 # 刷新月macd
#                 fresh_month_macd(code, mk)
#
#
# # 处理月macd
# def fresh_month_macd(code, mk):
#     mkr = mk['rq']
#     mmacds = stock_month_macd.select_interval(code, mkr, 2)
#     if not mmacds:
#         macd_util_v1.init_month_macd(code)
#         return
#     if len(mmacds) < 2:
#         print(code + ':长度小于2')
#         return
#     now_macd = mmacds[0]
#     pre_macd = mmacds[1]
#     if now_macd['rq'].month == mk['rq'].month:
#         macd_info = macd_util_v1.cal_macd_next_v1(pre_macd, mk['rq'], mk['sp'])
#         stock_month_macd.update(macd_info)
#     elif date_util.diff_days(now_macd['rq'], mkr) > 0:
#         macd_info = macd_util_v1.cal_macd_next_v1(now_macd, mk['rq'], mk['sp'])
#         stock_month_macd.insert(macd_info)
#     else:
#         print(code + 'error,error错误的数据注意')
#
#
# # 持久化监控数据
# def persistence_data():
#     print("persistence start")
#
#
# # 刷新市值
# def fresh_stock_val():
#     s_list = stock_info.selectall()
#     for s in s_list:
#         code = s['code']
#         flow = caiptal_util.get_flow(code)
#         stock_info.update_the_val(code, int(flow.market_value / 100000000), int(flow.circulation_value / 100000000))
#
#
# if __name__ == '__main__':
#     print('start')
#     fresh_stock_val()
#     print('end')
#     # s_list = [{'code': '688687'},
#     #           {'code': '688059'}
#     #           ]
#     # add_day_k(s_list)
